package com.coscoshipping.rams.demo.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.coscoshipping.rams.demo.entity.BusinessSalesStatistics;
import com.coscoshipping.rams.demo.mapper.BusinessSalesStatisticsMapper;
import com.coscoshipping.rams.demo.pojo.vo.BusinessSalesVO;
import com.coscoshipping.rams.demo.service.IBusinessSalesStatisticsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhaoyin.yang
 * @since 2025-04-19
 */
@Service
public class BusinessSalesStatisticsServiceImpl extends ServiceImpl<BusinessSalesStatisticsMapper, BusinessSalesStatistics> implements IBusinessSalesStatisticsService {

    /**
     * 保存或更新数据到数据库
     */
    @Override
    @DS("slave_1")
    @Transactional
    public void saveOrUpdateData(List<BusinessSalesVO> voList) {
        if (voList == null || voList.isEmpty()) {
            return;
        }

        // 转换为实体类列表
        List<BusinessSalesStatistics> entityList = voList.stream()
                .map(vo -> {
                    BusinessSalesStatistics entity = new BusinessSalesStatistics();
                    entity.setTabulationTime(vo.getTabulationTime());
                    entity.setItemname(vo.getItemname());
                    entity.setGroupname(vo.getGroupname());
                    entity.setTodaySumAfter(vo.getTodaySumAfter());
                    entity.setTodaySum(vo.getTodaySum());
                    entity.setMonthSum(vo.getMonthSum());
                    return entity;
                })
                .collect(Collectors.toList());

        // 批量插入或更新
        entityList.forEach(entity -> {
            // 判断是否存在相同记录
            BusinessSalesStatistics existingRecord = this.lambdaQuery()
                    .eq(BusinessSalesStatistics::getTabulationTime, entity.getTabulationTime())
                    .eq(BusinessSalesStatistics::getItemname, entity.getItemname())
                    .eq(StrUtil.isNotBlank(entity.getGroupname()),BusinessSalesStatistics::getGroupname, entity.getGroupname())
                    .one();

            if (existingRecord == null) {
                // 如果不存在，则插入
                this.save(entity);
            } else {
                // 如果存在，则忽略
                System.out.println("忽略重复数据: " + entity);
            }
        });
    }

}
